import path from 'path'
import dotenv from 'dotenv'
import userHome from 'user-home'
import rootCheck from 'root-check'
import semver from 'semver'
import colors from 'colors'
import { Command } from 'commander'
import { readFileSync } from 'fs'

// import pkg from '../package.json' assert { type: 'json' };
import constant from './const.js'
import { pathExistsSync } from 'path-exists'
import log from '@start-cli-dev/log'
import { getNpmSameVersion } from '@start-cli-dev/get-npm-info'
import init from '@start-cli-dev/init'
import exec from '@start-cli-dev/exec'

const pkg = JSON.parse(
  readFileSync(new URL('../package.json', import.meta.url))
)
function checkPkgVersion() {
  log.notice('cli', pkg.version)
}

// function checkNodeVersion() {
//   const currentVersion = process.version
//   const lowestVersion = constant.LOWEST_NODE_VERSION
//   if (!semver.gte(currentVersion, lowestVersion)) {
//     throw new Error(
//       colors.red(
//         `start-cli-dev 需要安装 v${lowestVersion} 及以上版本的 node.js`
//       )
//     )
//   }
// }

function checkRoot() {
  rootCheck()
}

// 判断用户主目录
function checkUserHome() {
  if (!userHome || !pathExistsSync(userHome)) {
    throw new Error(colors.red(`当前登录的用户主目录不存在`))
  }
}

function createDefaultConfig() {
  const cliConfig = {
    home: userHome
  }
  if (process.env.CLI_HOME) {
    cliConfig.cliHome = path.join(userHome, process.env.CLI_HOME)
  } else {
    cliConfig.cliHome = path.join(userHome, constant.DEFAULT_CLI_HOME)
  }
  process.env.CLI_HOME_PATH = cliConfig.cliHome
}
// 检查环境
function checkEnv() {
  const dotenvPath = path.resolve(userHome, '.env')
  if (pathExistsSync(dotenvPath)) {
    dotenv.config({
      path: path.resolve(userHome, '.env')
    })
  }
  createDefaultConfig()
  // log.verbose('环境变量', process.env.CLI_HOME_PATH)
}
// 检查npm包是否需要更新
async function checkGlobalUpdate() {
  // 1.获取当前版本号跟模块名
  const currentVersion = pkg.version
  const currentName = pkg.name
  const lastVersion = await getNpmSameVersion(currentVersion, currentName)
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      '更新提醒',
      `请手动更新${currentName},当前版本${currentVersion},最新版本${lastVersion}  
            更行命令 npm install -g ${currentName}
      `
    )
  }
  // 2.调用npm api ,获取所有的版本号
  // 3.提取所有的版本号，对比那些版本号是大于当前版本号的
  // 4.获取最新的版本号，提示用户更新到该版本
}

const program = new Command()
// 注册命令
function registerCommander() {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage('<commander> [options]')
    .version(pkg.version)
    .option('-d --debug', '是否开启调试模式', false)
    .option('-tp --targetPath <targetPath>', '是否指定本地调试文件路径', '')

  program.on('option:debug', () => {
    if (program.opts().debug) {
      process.env.LOG_LEVEL = 'verbose'
    } else {
      process.env.LOG_LEVEL = 'info'
    }
    log.level = process.env.LOG_LEVEL
    log.verbose('debug', 'test debug verbose')
  })

  // 监听targetPath
  program.on('option:targetPath', () => {
    process.env.CLI_TARGET_PATH = program.opts().targetPath
  })

  // 对未知命令进行监听
  program.on('command:*', obj => {
    // eslint-disable-next-line no-underscore-dangle
    const availableCommands = program.commands.map(item => item.name())
    log.error(colors.red(`未知命令: ${obj[0]}`))
    if (availableCommands.length) {
      log.info(colors.green(`可用的命令: ${availableCommands.join(',')}`))
    }
  })
  program
    .command('init [projectName]')
    .option('-f --force', '是否强制覆盖已有文件', false)
    .option('-t --test', '测试options', false)
    .action(exec)

  program.parse()
  // 没有输入命令打印出帮助文档
  if (program.args && program.args.length < 1) {
    program.outputHelp()
  }
}

async function prepare() {
  checkPkgVersion()
  // checkNodeVersion()
  checkRoot()
  checkUserHome()
  checkEnv()
  await checkGlobalUpdate()
}

export default async function core() {
  try {
    await prepare()
    registerCommander()
  } catch (e) {
    if (program.debug) {
      console.log(e) // debug 打印错误堆栈信息
    }
    log.error(e.message)
  }
}
